package com.vpen.spel.demo.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.vpen.spel.demo.annotation.SpelTest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/8/17 17:27
 */
@Slf4j
@Component
@Aspect
public class SpelTestAspect {


    @Pointcut("@annotation(com.vpen.spel.demo.annotation.SpelTest)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        // 获取注解
        SpelTest annotation = method.getAnnotation(SpelTest.class);

        // 获取方法上所有的参数
        Object[] args = joinPoint.getArgs();

        Map<String, Object> map = new HashMap<>(16);

        for (String expressionString : annotation.params()) {

            // 1.获取方法形参名字
            LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
            String[] paramNameArr = discoverer.getParameterNames(method);


            if (ObjectUtil.isNull(paramNameArr)) {
                System.out.println("没有参数");
                continue;
            }
            // 2.绑定参数到形参名字
            ExpressionParser parser = new SpelExpressionParser();
            StandardEvaluationContext context = new StandardEvaluationContext();
            for (int i = 0; i < paramNameArr.length; i++) {
                context.setVariable(paramNameArr[i], args[i]);
            }
            String value = parser.parseExpression(expressionString).getValue(context, String.class);
            map.put(expressionString, value);
        }

        System.out.println("我拦截到了东西");
        System.out.println(map);

        return joinPoint.proceed();
    }


}
